function [distance,point]=least_E_distance(Points);
%Points={x1,x2,x3...;y1,y2,y3...}, it is unsorted
P_size=size(Points);
if P_size(2)==2
    x_diff=Points(1,1)-Points(1,2);
    y_diff=Points(2,1)-Points(2,2);
    distance=sqrt(x_diff^2+y_diff^2);
    point=[0,0;0,0];
    return;
else if P_size(2)<2
        distance=+inf;
        point=[0,0;0,0];
        return;
    end
end
if P_size(1) ~= 2
    error('Points is not a 2xN matrix');
end
%divide
x_mid=Points(1,1)/2+Points(1,2)/2;

k=uint16(1);
k_left=uint16(1);
k_right=uint16(1);
for k=1:P_size(2)
    if Points(1,k)<x_mid
        P_left(:,k_left)=Points(:,k);
        k_left = k_left+1;
    else
        P_right(:,k_right)=Points(:,k);
        k_right=k_right+1;
    end
end
[l_distance,l_point]=least_E_distance(P_left);
[r_distance,r_point]=least_E_distance(P_right);
l_r_min=min(l_distance,r_distance);
[c_distance,c_point]=combine_left_right(P_left,P_right,l_r_min,x_mid);
distance=min(l_r_min,c_distance);
if distance == l_distance
    point=l_point;
else if distance== r_distance
        point=r_point;
    else
        point=c_point;
    end
end
end

function [distance,points]=combine_left_right(P_left,P_right,distance_min,x_mid);

x_min=x_mid-distance_min;
x_max=x_mid+distance_min;
distance=+inf;
points=[0,0;0,0];

l_size=size(P_left);
r_size=size(P_right);
j=uint16(1);
k=uint16(1);
%select the point where x_min<x<x_max
for j=1:l_size(2)
    if P_left(1,j)>=x_min && P_left(1,j)<=x_max
        l_selected(:,k)=P_left(:,j);
        k=k+1;
    end
end
k=uint16(1);
for j=1:r_size(2)
    if P_right(1,j)>=x_min && P_right(1,j)<=x_max
        r_selected(:,k)=P_right(:,j);
        k=k+1;
    end
end
l_size=size(l_selected);
r_size=size(r_selected);
min_distance=+inf;
tmp_distance=0;
for j=1:l_size(2)
    for k=1:r_size(2)
        tmp_distance=get_distance(l_selected(:,j), r_selected(:,k));
        if(tmp_distance<min_distance)
            points(:,1)=l_selected(:,j);
            points(:,2)=r_selected(:,j);
            min_distance=tmp_distance;
        end
    end
end
end

function distance=get_distance(A,B);
x_diff=A(1,1)-B(1,1);
y_diff=A(2,1)-B(2,1);
distance=sqrt(x_diff^2+y_diff^2);
end